#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include <pulse/simple.h>
#include <pulse/error.h>

#include "light_beat.h"
#include "bassbeat.h"
#include "options.h"

int runlight(lightoptions *opts)
{
        int error;
        pa_sample_spec ss = {
                .format = PA_SAMPLE_S16LE,
                .rate = opts->rate,
                .channels = 1
        };

        pa_simple *s = NULL;
        int16_t buf[opts->bufsize];
        sounddata * handler;

        /* Create the recording stream */
        if (!(s = pa_simple_new(NULL, "lightbeat", PA_STREAM_RECORD, opts->pulsedev, "record", &ss, NULL, NULL, &error))) {
                fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error));
                goto finish;
        }

        handler = sounddata_init(opts->bufsize / (sizeof(int16_t)), RATE);

        for (;;) {
                if (pa_simple_read(s, buf, sizeof(buf), &error) < 0) {
                        fprintf(stderr, __FILE__": pa_simple_read() failed: %s\n", pa_strerror(error));
                        goto finish;
                }
                handler = handle_sample(handler, buf);
        }

 finish:
        if (s)
                pa_simple_free(s);
        return 0;
}
